﻿using DDD.Core.Exceptions;
using DDD.Core.Exceptions.Bussines;
using DDD.Core.Result;
using Microsoft.AspNetCore.Diagnostics;

namespace DDD.Api
{
    internal class GlobalExceptionHandler : IExceptionHandler
    {
        private readonly ILogger<GlobalExceptionHandler> _logger;

        public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
        {
            _logger = logger;
        }

        public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
        {
            _logger.LogError($"exception occured:{exception.Message}");

            if (exception is UnSystemException)
            {
                httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
                string message = exception.Message;
                if (exception is VaildateException)
                {
                    message = string.Join(',', (exception as VaildateException)?.Errors.Select(c => $"{c.Property}:{c.Error}"));
                }

                await httpContext.Response.WriteAsJsonAsync(ApiResult.Failed(message));
            }
            else
            {
                httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                await httpContext.Response.WriteAsJsonAsync(ApiResult.Failed("系统异常"));
            }

            return true;
        }
    }
}
